package LeetCode.SlideWindow;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * @author : LdLtd
 * @Date : 2023/8/2
 * @Description:239. 滑动窗口最大值
 */
public class sliding_window_maximum {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {7, 6, 5, 4, 3, 2, 1};
        int k = 3;
        System.out.println(Arrays.toString(solution.maxSlidingWindow(nums, k)));
    }

    /*用单调队列维护，当新加入的值符合条件时，可以从队尾出然后加入新元素,这里用数组模拟队列*/
    static class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            int l = 0, r = -1, t = 0;
            int[] res = new int[nums.length - k + 1];
            int[] q = new int[nums.length];
            for (int i = 0; i < nums.length; i++) {
                //i-k+1是窗口的左边界，
                if (r >= l && q[l] < i - k + 1) l++;
                //如果新加入的元素是大的，就从队尾把元素一个一个的去除
                while (r >= l && nums[i] > nums[q[r]]) r--;
                //加入新元素
                q[++r] = i;
                if (i >= k - 1) res[i - k + 1] = nums[q[l]];
            }
            return res;

        }

        /*用linkedlist优化空间*/
        public int[] maxSlidingWindow1(int[] nums, int k) {
            LinkedList<Integer> q = new LinkedList<>();
            int[] res = new int[nums.length - k + 1];
            for (int i = 0; i < nums.length; i++) {
                while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) q.pollLast();
                q.addLast(i);
                //判断队首是否有效
                if (q.peek() <= i - k) q.poll();
                if (i >= k - 1) res[i - k + 1] = nums[q.peek()];
            }
            return res;
        }
    }
}

